package com.csx.micrometer.invoke.core.inbound.webflux;

import com.csx.micrometer.invoke.context.webflux.MicrometerWebFluxRequest;
import com.csx.micrometer.invoke.context.webflux.MicrometerWebFluxResponse;
import com.csx.micrometer.invoke.custom.TagsCustom;
import io.micrometer.core.instrument.Tags;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;

/**
 * @author cuisongxu
 * @date 2023/2/1 15:13
 */
@Component
public class MicrometerWebFluxHandlerInboundInterceptor implements WebFilter {

    /**
     * 标签定制器
     */
    private final List<TagsCustom> tagsCustoms;

    public MicrometerWebFluxHandlerInboundInterceptor(List<TagsCustom> tagsCustoms) {
        this.tagsCustoms = tagsCustoms;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        // Your custom implementation when api is hit and the request lands
        long startTime = System.currentTimeMillis();

        // 自定义tags
        Tags tags = Tags.of(Collections.emptyList());
        for (TagsCustom tagsCustom : tagsCustoms) {
            tags = tagsCustom.customTags(new MicrometerWebFluxRequest(exchange), new MicrometerWebFluxResponse(exchange), tags);
        }

        return chain.filter(exchange).doFinally(signalType -> {
            // Your custom implementation, when request-response exchange gets completed
            long totalTime = System.currentTimeMillis() - startTime;
            exchange.getAttributes().put("totalTime", totalTime);
            System.out.println("cost time: " + totalTime);
        });

    }
}
